// 应用状态管理
class AppState {
    constructor() {
        this.currentUser = null;
        this.token = null;
        this.users = JSON.parse(localStorage.getItem('users') || '[]');
    }

    // 保存用户数据到本地存储
    saveUsers() {
        localStorage.setItem('users', JSON.stringify(this.users));
    }

    // 登录
    async login(username, password) {
        return new Promise((resolve) => {
            setTimeout(() => {
                const user = this.users.find(u => u.username === username && u.password === password);
                if (user) {
                    this.currentUser = user;
                    this.token = this.generateToken();
                    resolve({ success: true, token: this.token });
                } else {
                    resolve({ success: false, message: '用户名或密码错误' });
                }
            }, 1000); // 模拟网络延迟
        });
    }

    // 注册
    async register(username, email, password) {
        return new Promise((resolve) => {
            setTimeout(() => {
                // 检查用户名是否已存在
                if (this.users.find(u => u.username === username)) {
                    resolve({ success: false, message: '用户名已存在' });
                    return;
                }

                // 检查邮箱是否已存在
                if (this.users.find(u => u.email === email)) {
                    resolve({ success: false, message: '邮箱已被注册' });
                    return;
                }

                // 创建新用户
                const newUser = {
                    id: Date.now(),
                    username,
                    email,
                    password,
                    createdAt: new Date().toISOString()
                };

                this.users.push(newUser);
                this.saveUsers();
                this.currentUser = newUser;
                this.token = this.generateToken();

                resolve({ success: true, token: this.token });
            }, 1000); // 模拟网络延迟
        });
    }

    // 生成模拟token
    generateToken() {
        return 'lakers_' + Math.random().toString(36).substr(2, 9) + '_' + Date.now();
    }

    // 登出
    logout() {
        this.currentUser = null;
        this.token = null;
    }
}

// 全局应用状态
const appState = new AppState();

// DOM 元素引用
const loginScreen = document.getElementById('loginScreen');
const registerScreen = document.getElementById('registerScreen');
const mainScreen = document.getElementById('mainScreen');

// 显示不同界面
function showLogin() {
    hideAllScreens();
    loginScreen.classList.add('active');
}

function showRegister() {
    hideAllScreens();
    registerScreen.classList.add('active');
}

function showMain() {
    hideAllScreens();
    mainScreen.classList.add('active');
    
    // 更新欢迎信息
    document.getElementById('welcomeUsername').textContent = appState.currentUser.username;
    document.getElementById('userToken').textContent = appState.token.substring(0, 20) + '...';
}

function hideAllScreens() {
    document.querySelectorAll('.screen').forEach(screen => {
        screen.classList.remove('active');
    });
}

// 登录表单处理
document.getElementById('loginForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const username = document.getElementById('loginUsername').value.trim();
    const password = document.getElementById('loginPassword').value.trim();
    const errorDiv = document.getElementById('loginError');
    const loginBtn = document.getElementById('loginBtn');
    const btnText = loginBtn.querySelector('.btn-text');
    const loading = loginBtn.querySelector('.loading');

    if (!username || !password) {
        showError(errorDiv, '请输入用户名和密码');
        return;
    }

    // 显示加载状态
    setLoadingState(loginBtn, btnText, loading, true);
    hideError(errorDiv);

    try {
        const result = await appState.login(username, password);
        
        if (result.success) {
            showMain();
        } else {
            showError(errorDiv, result.message);
        }
    } catch (error) {
        showError(errorDiv, '登录失败，请重试');
    } finally {
        setLoadingState(loginBtn, btnText, loading, false);
    }
});

// 注册表单处理
document.getElementById('registerForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const username = document.getElementById('registerUsername').value.trim();
    const email = document.getElementById('registerEmail').value.trim();
    const password = document.getElementById('registerPassword').value.trim();
    const errorDiv = document.getElementById('registerError');
    const registerBtn = document.getElementById('registerBtn');
    const btnText = registerBtn.querySelector('.btn-text');
    const loading = registerBtn.querySelector('.loading');

    if (!username || !email || !password) {
        showError(errorDiv, '请填写所有字段');
        return;
    }

    // 简单的邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        showError(errorDiv, '请输入有效的邮箱地址');
        return;
    }

    // 密码长度验证
    if (password.length < 6) {
        showError(errorDiv, '密码长度至少6位');
        return;
    }

    // 显示加载状态
    setLoadingState(registerBtn, btnText, loading, true);
    hideError(errorDiv);

    try {
        const result = await appState.register(username, email, password);
        
        if (result.success) {
            showMain();
        } else {
            showError(errorDiv, result.message);
        }
    } catch (error) {
        showError(errorDiv, '注册失败，请重试');
    } finally {
        setLoadingState(registerBtn, btnText, loading, false);
    }
});

// 登出功能
function logout() {
    appState.logout();
    
    // 清空表单
    document.getElementById('loginForm').reset();
    document.getElementById('registerForm').reset();
    
    // 隐藏错误信息
    hideError(document.getElementById('loginError'));
    hideError(document.getElementById('registerError'));
    
    showLogin();
}

// 工具函数
function showError(errorDiv, message) {
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
}

function hideError(errorDiv) {
    errorDiv.style.display = 'none';
}

function setLoadingState(button, textElement, loadingElement, isLoading) {
    if (isLoading) {
        button.disabled = true;
        textElement.style.display = 'none';
        loadingElement.style.display = 'block';
    } else {
        button.disabled = false;
        textElement.style.display = 'block';
        loadingElement.style.display = 'none';
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 默认显示登录界面
    showLogin();
    
    // 添加一些演示用户数据
    if (appState.users.length === 0) {
        appState.users = [
            {
                id: 1,
                username: 'demo',
                email: 'demo@example.com',
                password: '123456',
                createdAt: new Date().toISOString()
            },
            {
                id: 2,
                username: 'lakers',
                email: 'lakers@nba.com',
                password: 'lakers2024',
                createdAt: new Date().toISOString()
            }
        ];
        appState.saveUsers();
    }
});

// 添加键盘事件支持
document.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
        const activeScreen = document.querySelector('.screen.active');
        if (activeScreen) {
            const form = activeScreen.querySelector('form');
            if (form) {
                form.dispatchEvent(new Event('submit'));
            }
        }
    }
});

// 添加输入框焦点效果
document.querySelectorAll('input').forEach(input => {
    input.addEventListener('focus', () => {
        input.parentElement.classList.add('focused');
    });
    
    input.addEventListener('blur', () => {
        input.parentElement.classList.remove('focused');
    });
});